﻿

#region Using Statements

using UnityEngine;
using System.Collections.Generic;

#endregion


/// <summary>
/// 
/// </summary>
public class BoomerangMaster : ObjectScript
{

    #region Members

    public int boomerangs = 1;

    public float throwForce = 250.0f;

    public float offsetDistance = 0.5f;

    public float mouseRayDepth = 0.0f;

    public float inheritVelocity = 0.5f;

    public float recoilForce = 500.0f;

    public Transform releasePoint;

    public GameObject boomerangPrefab;

    #endregion


    #region Init

    /// <summary>
    /// 
    /// </summary>
    protected virtual void Awake()
    {

    }


    /// <summary>
    /// 
    /// </summary>
    protected virtual void Start()
    {

    }

    #endregion


    #region Update

    /// <summary>
    /// 
    /// </summary>
    protected virtual void Update()
    {
        // Fire boomerangs off like it's yo birthday
        if (Input.GetButtonDown("Fire1") && boomerangs > 0)
        {
            if (boomerangPrefab != null)
            {
                Vector3 mouseWorldLoc = Util.MouseLocation2D(Camera.main, mouseRayDepth);

                Vector3 release = releasePoint == null ? transform.position : releasePoint.position;
                Vector3 throwDiff = mouseWorldLoc - release;
                Vector3 throwDir = throwDiff.normalized;

                // prevent throwing boomerangs into walls (will bug out hard)
                if (!Physics.Raycast(transform.position, throwDir, offsetDistance))
                {
                    Vector3 spawnLoc = release + throwDir * offsetDistance;
                    GameObject boomy = (GameObject)Instantiate(boomerangPrefab, spawnLoc, Quaternion.identity);
                    boomy.GetComponent<Boomerang>().master = gameObject;

                    boomy.rigidbody2D.velocity = rigidbody2D.velocity * inheritVelocity;
                    boomy.rigidbody2D.AddForce(throwDir * throwForce);

                    boomerangs--;

                    if (rigidbody2D != null)
                        rigidbody2D.AddForce(-recoilForce * throwDir);
                }
            }
        }
    }

    #endregion


    #region Catch

    /// <summary>
    /// 
    /// </summary>
    void OnHitByBoomerang(Boomerang boomy)
    {
        Destroy(boomy.gameObject);
        boomerangs++;
    }

    #endregion

}